import React, { useEffect, useMemo, useState } from "react";
import cls from "@/styles/pages/Gantt.module.scss";
import { MedScheduler } from "@/feature/MedScheduler/MedScheduler";
import { generateScheduleReport, useEvents } from "@/api/events";
import { TimelineGroupBase, TimelineItemBase } from "react-calendar-timeline";
import { useUsers } from "@/api/users";
import { convertEventTime, EVENT_DATA } from "@/pages/gantt/helpers";
import { Button } from "@/ui/Button/Button";
import { useSearchParams } from "react-router-dom";
import {
  approveMonthById,
  getPrediction,
  getPredictionById,
} from "@/api/prediction";
import moment from "moment";
import { getMonthIdByStatus } from "@/feature/NewEventsTable/helper";

const params = new URLSearchParams({ limit: "99999", offset: "0" });
const mapper: Record<string, string> = {
  approved: "Утвержденное расписание",
  not_approved: "Не утвержденное расписание",
  temporary: "Временное расписание",
};

const Gantt = () => {
  const [searchParams] = useSearchParams();

  const [, users] = useUsers(params);
  const [monthOffset, setMonthOffset] = useState(0);
  const [monthId, setMonthId] = useState(0);
  const [status, setStatus] = useState("not_approved");
  const [initialIdSet, setInitialIdSet] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isApprovedLoading, setIsApprovedLoading] = useState(false);

  useEffect(() => {
    if (initialIdSet) return;
    getPredictionById(searchParams.get("monthId")).then((res) => {
      const diff = moment()
        .set("month", res.month)
        .set("year", res.year)
        .startOf("month")
        .diff(moment().startOf("month"), "months");
      setMonthOffset(diff < 0 ? diff - 1 : diff + 1);
      setInitialIdSet(true);
    });
  }, [monthId]);

  useEffect(() => {
    if (isApprovedLoading) return;
    const currMonth = moment().add(monthOffset, "month").get("month");
    const currYear = moment().add(monthOffset, "month").get("year");

    setIsLoading(true);
    getPrediction(
      new URLSearchParams({
        month: String(currMonth + 1),
        year: String(currYear),
      })
    )
      .then((res) => {
        const m = getMonthIdByStatus(res.results);
        if (!m) return;
        setMonthId(m.id);
        setStatus(m.status);
      })
      .finally(() => {
        setTimeout(() => {
          setIsLoading(false);
        }, 500);
      });
  }, [monthOffset, isApprovedLoading]);

  const eventParams = useMemo(() => {
    return new URLSearchParams({
      month: String(monthId),
      limit: "99999",
    });
  }, [monthId]);
  const [data, eventsData, eventsIsLoading, setData] = useEvents(eventParams);

  const usersGroups = useMemo<TimelineGroupBase[]>(() => {
    if (!users) return [];
    return users.map((u) => {
      return {
        id: u.id,
        title: `${u.first_name} ${u.last_name}`,
      };
    });
  }, [users]);

  const eventsNormalized = useMemo<TimelineItemBase<number>[]>(() => {
    if (!eventsData) return [];
    return eventsData.map((item) => {
      const k = item.kind.replace(" ", "_");

      return {
        start_time: convertEventTime(item),
        end_time: convertEventTime(item, true),
        title: EVENT_DATA[k].title,
        group: item.user,
        id: item.id,
        canResize: "both",
        canMove: false,
        itemProps: {
          style: {
            background: EVENT_DATA[k].backgroundColor,
            borderColor: item.viewed ? EVENT_DATA[k].backgroundColor : "red",
            borderWidth: "2px",
            zIndex: item.kind === "work_delta" ? 1000 : 1,
            borderRadius: "5px", // Add this line to round the corners
          },
        },
      };
    });
  }, [eventsData]);
  return (
    <div className="page-wrapper">
      <div className={cls.title}>
        Статус расписания на этот месяц: {mapper[status]}
      </div>
      <div className={cls.btns}>
        <div className={cls.monthBtns}>
          <Button onClick={() => setMonthOffset((p) => p - 1)}>
            Предыдущий месяц
          </Button>
          <Button onClick={() => setMonthOffset((p) => p + 1)}>
            Следующий месяц
          </Button>
        </div>
        <div className={cls.monthBtns}>
          <Button
            onClick={() => {
              const m = moment().add(monthOffset, "month").get("month");
              const y = moment().add(monthOffset, "month").get("year");
              generateScheduleReport(m + 1, y);
            }}
          >
            Скачать
          </Button>
          {status !== "approved" && (
            <Button
              onClick={() => {
                setIsApprovedLoading(true);
                approveMonthById(monthId).finally(() => {
                  setIsApprovedLoading(false);
                });
              }}
            >
              Утвердить
            </Button>
          )}
        </div>
      </div>
      {(eventsIsLoading || isLoading) && (
        <div className="lds-wrap">
          <div className="lds-dual-ring" />
        </div>
      )}
      {!isLoading && !eventsIsLoading && (
        <MedScheduler
          data={data}
          setData={setData}
          eventsNormalized={eventsNormalized}
          groups={usersGroups}
          monthOffset={monthOffset}
        />
      )}
    </div>
  );
};

export default Gantt;
